package offer_test_20;

import java.util.Arrays;

//输入一个整数数组，实现一个函数来调整该函数数组中数字的顺序，使得所有奇数位于数组的前半部分，所有的偶数位于数组的后半部分。
public class fourteen_ReorderArray {
	public static void main(String[] args) {
		int[] array = { 1, 3, 4, 23, 34, 56, 78, 809 };
		Judge j=new fourteen_ReorderArray().new Judge();
		System.out.println(Arrays.toString(sort(array)));
		System.out.println(Arrays.toString(sort2(array, j)));
	}

	public static int[] sort(int[] input) {
		int head = 0;
		int tail = input.length - 1;
		while (head < tail) {
			while (head < tail&&(input[head] & 1) == 0 && (input[tail] & 1) == 0) {
				tail--;
			}
			while (head < tail&&(input[head] & 1) == 0 && (input[tail] & 1) == 1) {
				int temp=input[tail];
				input[tail]=input[head];
				input[head]=temp;
				tail--;
				head++;
			}
			while (head < tail&&(input[head] & 1) == 1 && (input[tail] & 1) == 0) {
				tail--;
				head++;
			}
			while (head < tail&&(input[head] & 1) == 1 && (input[tail] & 1) == 1) {
				head++;
			}
		}
		return input;
	}
	//方法2 解耦程度更高
	public static int[] sort2(int[] input,Judge judge){
		int head = 0;
		int tail = input.length - 1;
		while (head < tail) {
			while (head < tail&&judge.isEven(input[tail])) {
				tail--;
			}
			while (head < tail&&!judge.isEven(input[head])) {
				head++;
			}
			if(head<tail){
				int temp=input[tail];
				input[tail]=input[head];
				input[head]=temp;
			}
		}
		return input;
	}
	class Judge{
		
		public Judge() {
		}

		public boolean isEven(int n){
			if((n&1)==1){
				return false;
			}else{
				return true;
			}
		}
	}
}
